package com.joe.xl.common.util.redis;

import java.util.Collections;

public class RedisLock {
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;

    public static Boolean acquire(String lockKey, String requestId, long expireTime) {
        try {
            while (true) {
//                if (LOCK_SUCCESS.equals(RedisClient.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime))) {
//                    return true;
//                }
                Thread.sleep(100);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public static boolean unlock(String lockKey, String requestId) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//        Object result = RedisClient.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
//        if (RELEASE_SUCCESS.equals(result)) {
//            return true;
//        }
        return false;
    }
}
